<?php

namespace App\Jobs\Zhunya;

use App\Models\Api\Rectification as RectificationModel;
use App\Models\Api\User;
use App\Models\Api\Orders;
use App\Models\Api\MessageCenter;
use App\Tools\Push;
use App\Tools\Rectification;
use DB,Cache;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class RectificationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $jobData;

    /**
     * Create a new job instance.
     *
     * @param array $jobData
     */
    public function __construct(array $jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function task1()
    {
      $jobData = $this->jobData;
      try
        {
            // centos获取系统ip
            exec('/sbin/ifconfig eth0 | sed -n \'s/^ *inet \\([0-9.]\\{7,\\}\\) .*$/\\1/p\'', $arr1);

            exec('hostname', $arr2);

            $host = $arr1[0] ?? ($arr2[0] ?? '');
        }
        catch (\Exception $e)
        {
            $host = '';
//            print("获取ip失败:{$e->getMessage()}" . PHP_EOL);
//            \Log::info('获取ip失败:' . $e->getMessage());
        }
        \Log::info($jobData);
        $jobInfo = "uid:{$jobData['recode'][0]['uid']} rid:{$jobData['recode'][0]['id']} name:{$jobData['recode'][0]['name']} ";
      //  var_dump($jobInfo);die;
        if ($jobData['type'] == 'year')
        {
            $jobInfo .= '年运 ';
        } else
        {
            $jobInfo .= '月运 ';
        }

        print("【{$host}】" . PHP_EOL . $jobInfo . "计算{$jobData['start_time'][0]}开始时间： " . date('Y-m-d H:i:s') . PHP_EOL);

        \Log::info("【{$host}】" . PHP_EOL . $jobInfo . "运势计算{$jobData['start_time'][0]}开始时间： " . date('Y-m-d H:i:s'));

        // 计算数据，并入库、写入缓存
        $this->fireData($jobData);

        print("【{$host}】" . PHP_EOL . $jobInfo . "运势计算{$jobData['start_time'][0]}结束时间 " . date('Y-m-d H:i:s') . PHP_EOL);
        \Log::info("【{$host}】" . PHP_EOL . $jobInfo . "运势计算{$jobData['start_time'][0]}结束时间 " . date('Y-m-d H:i:s'));

        // 更新订单状态为，计算完成
        if (isset($jobData['oid']) && $jobData['oid'] && isset($jobData['status']))
        {
            try
            {
                $OrderModel = new Orders();
                $OrderModel->where('id', $jobData['oid'])->update(['status' => 4]);

                Cache::forget('u' . $jobData['recode'][0]['uid'] . $OrderModel::ORDER_INFO_ID . $jobData['order_id']);
              
                $db_update_status = true;
            }
            catch (\Exception $e)
            {
                $db_update_status = false;
                print("更新订单id:{$jobData['oid']}状态失败" . PHP_EOL);
                \Log::info($jobData['type'] . '更新订单状态失败：' . $e->getMessage());
            }
        } elseif (isset($jobData['aid']) && $jobData['aid'])
        {
            // 后台赠送时,修改状态
            try
            {
                (new AwardUser())->where('aid',$jobData['aid'])->update(['status' => 1]);

                Cache::forget($jobData['recode'][0]['uid'] .'_'. $jobData['recode'][0]['id']. '_award_fortune_' . $jobData['ftype']);

                $db_update_status = true;
            }
            catch (\Exception $e)
            {
                $db_update_status = false;
                print("更新订单id:{$jobData['oid']}状态失败" . PHP_EOL);
                \Log::info($jobData['type'] . '更新订单状态失败：' . $e->getMessage());
            }
        }  elseif (in_array($jobData['recode'][0]['uid'], config('vip')))
        {
            // 后台赠送时,修改状态
            try
            {
                $db_update_status = true;
            }
            catch (\Exception $e)
            {
                $db_update_status = false;
                print("更新订单id:{$jobData['oid']}状态失败" . PHP_EOL);
                \Log::info($jobData['type'] . '更新订单状态失败：' . $e->getMessage());
            }
        }else
        {
            $db_update_status = false;
            print("异常队列信息: " . PHP_EOL . var_export($jobData, true) . PHP_EOL);
            \Log::info("异常队列信息: " . PHP_EOL . var_export($jobData, true) . PHP_EOL);
        }

        if ($db_update_status === true)
        {
            // PUSH推送
            $userinfo = (new User())->getUserinfo(['id' => $jobData['recode'][0]['uid']]);

            if ($userinfo && $userinfo['regid'] != '')
            {
                try
                {
                    (new Push())->pushSpecial($userinfo['regid'], '您购买的' . $jobData['recode'][0]['name'] . '的运势' . $jobData['start_time'][0] . '已经计算完成了，点击查看运势详情！', [
                        'action' => 'fortune_for_' . $jobData['type'],
                        'rid' => $jobData['recode'][0]['id'],
                        'time' => $jobData['start_time'][0]
                    ]);
                }
                catch (\Exception $e)
                {
                    print($jobInfo . "运势计算{$jobData['start_time'][0]}完成推送失败" . PHP_EOL);
                    \Log::info($jobInfo . '运势计算完成推送失败：' . $e->getMessage());
                }
            }
            // 短信通知
            if ($userinfo && $userinfo['tel'] != '' && config('queue.fortune_sendsms') == 1)
            {
                try
                {
                    $recode_names = '「';
                    foreach ($jobData['recode'] as $re) $recode_names .= $re['name'] . '、';
                    $recode_names = rtrim($recode_names, '、');
                    $recode_names .= '」';

                    $fortune_times = $jobData['start_time'][0];

                    if (count($jobData['start_time']) > 1)
                    {
                        $fortune_times .= '至' . end($jobData['start_time']);
                    }

                    $sms_param = $recode_names . '的' . $fortune_times . '运势';

                    $sendSmsResult = sendSms($userinfo['tel'], ['orderId' => $sms_param], config('aliyun.dayu_fortune_code'));

                    if (!empty($sendSmsResult) && $sendSmsResult['Code'] != 'OK')
                    {
                        print($jobInfo . '运势计算完成短信通知失败:' . $sendSmsResult['Message'] . PHP_EOL);
                        \Log::info($jobInfo . '运势计算完成短信通知失败：' . $sendSmsResult['Message']);
                    }
                }
                catch (\Exception $e)
                {
                    print($jobInfo . '运势计算完成短信通知失败' . PHP_EOL);
                    \Log::info($jobInfo . '运势计算完成短信通知失败：' . $e->getMessage());
                }
            }
            
          //  Cache::forget('u' . $jobData['recode'][0]['uid'] . $OrderModel::ORDER_INFO_ID . $jobData['order_id']);
            
            // 消息中心添加信息
            $messageData = [
                'uid' => $userinfo['id'],
                'type' => 2,
                'cid' => 3,// 年运月运
                'title' => '运势计算完成',
                'content' => '您购买的' . $jobData['recode'][0]['name'] . '的运势' . $jobData['start_time'][0] . '已经计算完成了，点击查看运势详情！',
                'link' => 'fortune_for_' . $jobData['type'] . "?rid=" . $jobData['recode'][0]['id'] . "&time=" . $jobData['start_time'][0],
                'target' => "local",
            ];

            //添加消息
            (new MessageCenter())->pushMessage($messageData);

            print("「{$userinfo['tel']}」任务执行成功，删除该任务！" . PHP_EOL);

            //$job->delete();
        } else
        {
            print($jobInfo . "任务执行失败，删除该任务！" . PHP_EOL);
            print("异常队列信息: " . PHP_EOL . var_export($jobData, true) . PHP_EOL);
            \Log::info("异常队列信息: " . PHP_EOL . var_export($jobData, true) . PHP_EOL);
            //$job->delete();
        }
        return;
    }
}
